#!/usr/bin/env bash

set -e
shopt -s extglob # needed for rm everything but x
echo "Working directory: $PWD"

GENDOC_EXTRA_ARGS=$@
GIT_HEAD=$(git rev-parse HEAD) # save current head for commit message in scala/dotty.epfl.ch
PREVIOUS_SNAPSHOTS_DIR="$PWD/../prev_snapshots"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >& /dev/null && pwd)"
SITE_OUT_DIR="$PWD/docs/_site"

### Obtain the previous versions of the website ###
if [ -d "$PREVIOUS_SNAPSHOTS_DIR" ]; then
  rm -rf "$PREVIOUS_SNAPSHOTS_DIR"
fi

mkdir -pv "$PREVIOUS_SNAPSHOTS_DIR"
git remote add doc-remote "https://github.com/scala/dotty.epfl.ch.git"
git fetch doc-remote main
git checkout doc-remote/main
(cp -vr [03].*/ "$PREVIOUS_SNAPSHOTS_DIR"; true)  # Don't fail if no `3.*` found to copy
git checkout "$GIT_HEAD"

### Generate the current snapshot of the website ###
# this command will generate docs in $PWD/docs/_site
SBT="$SCRIPT_DIR/sbt"
"$SBT" "scaladoc/generateScalaDocumentation docs/_site"

# make sure that the previous command actually succeeded
if [ ! -d "$SITE_OUT_DIR" ]; then
  echo "Output directory did not exist: $SITE_OUT_DIR" 1>&2
  exit 1
fi

### Move previous versions' snapshots to _site ###
mv -v "$PREVIOUS_SNAPSHOTS_DIR"/* "$SITE_OUT_DIR"
rm -rf "$PREVIOUS_SNAPSHOTS_DIR"
